<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="创建日期" prop="createdAtRange">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker
              v-model="searchInfo.createdAtRange"
              class="w-[380px]"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item label="服务" prop="serviceType">
          <el-select v-model="searchInfo.serviceType" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.serviceType=undefined}">
            <el-option v-for="(item,key) in All_servicesOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="searchInfo.status" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.status=undefined}">
            <el-option v-for="(item,key) in statusOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="待处理人" prop="processor">
          <el-input v-model="searchInfo.processor" placeholder="搜索条件" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery=true" v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery=false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog()">新增</el-button>
        <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
      </div>

      <el-table
          ref="multipleTable"
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableData"
          row-key="ID"
          @selection-change="handleSelectionChange"
          @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column sortable align="left" label="日期" prop="created_at" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="单号" prop="intelligentMaintenanceNum" width="120" />
        <el-table-column align="left" label="服务" prop="serviceType" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.serviceType,All_servicesOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="设备(台)" prop="equipmentCount" width="120" />
        <el-table-column align="left" label="状态" prop="status" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" :class="getStatusClass(scope.row.status)" effect="plain">
              {{ filterDict(scope.row.status,statusOptions) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="待处理人" prop="processor" width="120" />
        <el-table-column sortable align="left" label="申请日期" prop="applicationDate" width="180">
          <template #default="scope">{{ formatDate(scope.row.applicationDate) }}</template>
        </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
          <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
              <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看
            </el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="updateIntelligentMaintenanceFunc(scope.row)">编辑</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="gva-pagination">
        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10,15, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
        <el-form-item label="单号:" prop="intelligentMaintenanceNum">
          <el-input v-model="formData.intelligentMaintenanceNum" :clearable="true" placeholder="请输入单号" />
        </el-form-item>
        <el-form-item label="服务:" prop="serviceType">
          <el-select v-model="formData.serviceType" placeholder="请选择服务" style="width:100%" filterable :clearable="true">
            <el-option v-for="(item,key) in All_servicesOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备(台):" prop="equipmentCount">
          <el-input v-model.number="formData.equipmentCount" :clearable="true" placeholder="请输入设备(台)" />
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width:100%" filterable :clearable="true">
            <el-option v-for="(item,key) in statusOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="待处理人:" prop="processor">
          <el-input v-model="formData.processor" :clearable="true" placeholder="请输入待处理人" />
        </el-form-item>
        <el-form-item label="申请日期:" prop="applicationDate">
          <el-date-picker v-model="formData.applicationDate" type="date" style="width:100%" placeholder="选择日期" :clearable="true" />
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="单号">
          {{ detailFrom.intelligentMaintenanceNum }}
        </el-descriptions-item>
        <el-descriptions-item label="服务">
          {{ detailFrom.serviceType }}
        </el-descriptions-item>
        <el-descriptions-item label="设备(台)">
          {{ detailFrom.equipmentCount }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ detailFrom.status }}
        </el-descriptions-item>
        <el-descriptions-item label="待处理人">
          {{ detailFrom.processor }}
        </el-descriptions-item>
        <el-descriptions-item label="申请日期">
          {{ detailFrom.applicationDate }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  createIntelligentMaintenance,
  deleteIntelligentMaintenance,
  deleteIntelligentMaintenanceByIds,
  updateIntelligentMaintenance,
  findIntelligentMaintenance,
  getIntelligentMaintenanceList
} from '@/api/intelligent_maintenances/intelligentMaintenance'

import { getDictFunc, formatDate, filterDict } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useAppStore } from "@/pinia"

defineOptions({
  name: 'IntelligentMaintenance'
})

const btnLoading = ref(false)
const appStore = useAppStore()
const showAllQuery = ref(false)
const All_servicesOptions = ref([])
const statusOptions = ref([])
const formData = ref({
  intelligentMaintenanceNum: '',
  serviceType: '',
  equipmentCount: undefined,
  status: '',
  processor: '',
  applicationDate: new Date(),
})

const rule = reactive({})
const elFormRef = ref()
const elSearchFormRef = ref()
const page = ref(1)
const total = ref(0)
const pageSize = ref(15)
const tableData = ref([])
const searchInfo = ref({})
const multipleSelection = ref([])
const dialogFormVisible = ref(false)
const detailShow = ref(false)
const type = ref('')
const detailFrom = ref({})

// 状态标签样式方法
const getStatusTagType = (status) => {
  switch(status) {
    case '2':
      return 'warning'
    case '3':
      return 'success'
    case '4':
      return 'danger'
    default:
      return ''
  }
}

const getStatusClass = (status) => {
  switch(status) {
    case '5':
      return 'pending-review'
    default:
      return ''
  }
}

const sortChange = ({ prop, order }) => {
  const sortMap = {
    CreatedAt: "CreatedAt",
    ID: "ID",
    applicationDate: 'application_date',
  }

  let sort = sortMap[prop]
  if(!sort){
    sort = prop.replace(/[A-Z]/g, match => `_${match.toLowerCase()}`)
  }

  searchInfo.value.sort = sort
  searchInfo.value.order = order
  getTableData()
}

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getIntelligentMaintenanceList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const setOptions = async () => {
  All_servicesOptions.value = await getDictFunc('All_services')
  statusOptions.value = await getDictFunc('status')
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteIntelligentMaintenanceFunc(row)
  })
}

const onDelete = async() => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
    multipleSelection.value.map(item => {
      IDs.push(item.ID)
    })
    const res = await deleteIntelligentMaintenanceByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

const updateIntelligentMaintenanceFunc = async(row) => {
  const res = await findIntelligentMaintenance({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

const deleteIntelligentMaintenanceFunc = async (row) => {
  const res = await deleteIntelligentMaintenance({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    intelligentMaintenanceNum: '',
    serviceType: '',
    equipmentCount: undefined,
    status: '',
    processor: '',
    applicationDate: new Date(),
  }
}

const enterDialog = async () => {
  btnLoading.value = true
  elFormRef.value?.validate( async (valid) => {
    if (!valid) return btnLoading.value = false
    let res
    switch (type.value) {
      case 'create':
        res = await createIntelligentMaintenance(formData.value)
        break
      case 'update':
        res = await updateIntelligentMaintenance(formData.value)
        break
      default:
        res = await createIntelligentMaintenance(formData.value)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const openDetailShow = () => {
  detailShow.value = true
}

const getDetails = async (row) => {
  const res = await findIntelligentMaintenance({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data
    openDetailShow()
  }
}

const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}

// 初始化
getTableData()
setOptions()
</script>

<style scoped>
/* 状态标签样式 */
.el-tag {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
  border-width: 1px;
}

/* 待审核 - 黄色 */
.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

/* 待复核 - 蓝色 */
.el-tag.pending-review {
  background-color: #f0f9ff;
  border-color: #d9ecff;
  color: #409eff;
}

/* 已审核 - 绿色 */
.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

/* 已取消 - 红色 */
.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}

/* 表格操作按钮样式 */
.table-button {
  margin-right: 8px;
}

/* 搜索框样式 */
.gva-search-box {
  margin-bottom: 15px;
}

/* 表格容器样式 */
.gva-table-box {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 分页样式 */
.gva-pagination {
  margin-top: 15px;
  text-align: right;
}
</style>